// pages/password/password.js
import { changePassword } from '../../api/person'

Page({
  data: {
    newPassword: '',
    confirmPassword: '',
    isFormValid: false,
    passwordStatus: '', // success, error
    confirmStatus: '', // success, error
  },

  onLoad(options) {
    
  },

  onUnload() {
    
  },

  // 新密码输入
  onNewPasswordInput(e) {
    const value = e.detail.value;
    const isValid = this.validatePassword(value);
    
    this.setData({
      newPassword: value,
      passwordStatus: value ? (isValid ? 'success' : 'error') : ''
    }, () => {
      this.validateForm();
    });
  },

  // 确认密码输入
  onConfirmPasswordInput(e) {
    const value = e.detail.value;
    const { newPassword } = this.data;
    const isMatch = value === newPassword && value !== '';
    
    this.setData({
      confirmPassword: value,
      confirmStatus: value ? (isMatch ? 'success' : 'error') : ''
    }, () => {
      this.validateForm();
    });
  },

  // 密码输入框聚焦
  onPasswordFocus() {
    if (this.data.newPassword) {
      const isValid = this.validatePassword(this.data.newPassword);
      this.setData({
        passwordStatus: isValid ? 'success' : 'error'
      });
    }
  },

  // 密码输入框失去焦点
  onPasswordBlur() {
    if (!this.data.newPassword) {
      this.setData({ passwordStatus: '' });
    }
  },

  // 确认密码输入框聚焦
  onConfirmFocus() {
    if (this.data.confirmPassword) {
      const isMatch = this.data.confirmPassword === this.data.newPassword;
      this.setData({
        confirmStatus: isMatch ? 'success' : 'error'
      });
    }
  },

  // 确认密码输入框失去焦点
  onConfirmBlur() {
    if (!this.data.confirmPassword) {
      this.setData({ confirmStatus: '' });
    }
  },

  // 验证表单
  validateForm() {
    const { newPassword, confirmPassword } = this.data;
    
    // 检查密码是否符合规则
    const isPasswordValid = this.validatePassword(newPassword);
    
    // 检查两次密码是否一致
    const isPasswordMatch = newPassword === confirmPassword && newPassword !== '';
    
    this.setData({
      isFormValid: isPasswordValid && isPasswordMatch
    });
  },

  // 验证密码规则
  validatePassword(password) {
    if (password.length < 8 || password.length > 20) {
      return false;
    }
    
    // 检查是否包含字母
    const hasLetter = /[a-zA-Z]/.test(password);
    
    // 检查是否包含特殊符号
    const hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password);
    
    return hasLetter && hasSpecialChar;
  },

  // 保存密码
  async onSave() {
    const { newPassword, confirmPassword, isFormValid } = this.data;
    
    if (!isFormValid) {
      wx.showToast({
        title: '请填写正确的密码格式',
        icon: 'none'
      });
      return;
    }

    if (newPassword !== confirmPassword) {
      wx.showToast({
        title: '两次输入的密码不一致',
        icon: 'none'
      });
      return;
    }

    // 获取用户信息
    const studentInfo = wx.getStorageSync('studentInfo');
    if (!studentInfo || !studentInfo.studentNo) {
      wx.showToast({
        title: '用户信息获取失败，请重新登录',
        icon: 'none'
      });
      return;
    }

    // 显示旧密码输入弹窗
    this.showOldPasswordDialog();
  },

  // 显示旧密码输入弹窗
  showOldPasswordDialog() {
    wx.showModal({
      title: '验证身份',
      content: '请输入当前密码进行身份验证',
      editable: true,
      placeholderText: '请输入当前密码',
      confirmText: '确认',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          const oldPassword = res.content;
          if (!oldPassword) {
            wx.showToast({
              title: '请输入当前密码',
              icon: 'none'
            });
            return;
          }
          // 调用修改密码接口
          this.updatePasswordRequest(oldPassword);
        }
      }
    });
  },

  // 调用修改密码接口
  async updatePasswordRequest(oldPassword) {
    const { newPassword, confirmPassword } = this.data; // 获取确认密码
    const studentInfo = wx.getStorageSync('studentInfo');

    console.log('修改密码请求参数:', {
      studentNo: studentInfo.studentNo,
      oldPassword: '***', // 不记录真实密码
      newPassword: '***',
      confirmPassword: '***'
    });

    wx.showLoading({
      title: '修改中...',
      mask: true
    });

    try {
      const res = await changePassword({
        studentNo: studentInfo.studentNo,
        oldPassword: oldPassword,
        newPassword: newPassword,
        confirmPassword: confirmPassword // 添加确认密码参数
      });

      wx.hideLoading();

      console.log('修改密码完整响应:', res);

      // 根据CommonResult结构处理响应
      if (res.success) {
        wx.showToast({
          title: '密码修改成功',
          icon: 'success',
          duration: 2000
        });

        // 清空表单
        this.setData({
          newPassword: '',
          confirmPassword: '',
          passwordStatus: '',
          confirmStatus: '',
          isFormValid: false
        });

        // 返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        // 修改失败
        wx.showToast({
          title: res.message || '密码修改失败',
          icon: 'none',
          duration: 2000
        });
      }
    } catch (err) {
      wx.hideLoading();
      console.error('修改密码请求失败:', err);
      
      let errorMsg = '网络错误，请重试';
      if (err.message && err.message.includes('确认密码不能为空')) {
        errorMsg = '请确认新密码和确认密码一致';
      } else if (err.statusCode === 400) {
        errorMsg = '请求参数错误';
      } else if (err.statusCode === 401) {
        errorMsg = '身份验证失败，请检查旧密码';
      } else if (err.statusCode === 500) {
        errorMsg = '服务器错误';
      }

      wx.showToast({
        title: errorMsg,
        icon: 'none',
        duration: 2000
      });
    }
  }
})